package com.aiyige.page.user;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.dao.InfoModelDao;
import com.aiyige.base.db.dao.NormalVideoModelDao;
import com.aiyige.base.db.dao.PhotoModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.InfoModel;
import com.aiyige.base.db.table.NormalVideoModel;
import com.aiyige.base.db.table.PhotoModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.base.eventbus.EventPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventServerChangeMomentStatus;
import com.aiyige.base.eventbus.EventUploadUpdate;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.detail.DetailPage;
import com.aiyige.page.home.adapter.HomeAdapter;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.page.user.adapter.DynamicAdapter;
import com.aiyige.page.user.model.DynamicMoment;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.LocalServerCommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DynamicPage#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DynamicPage extends BaseFragment implements CommonDataView.RetrofitStub {
    @BindView(R.id.cdv)
    CommonDataView cdv;
    Unbinder unbinder;
    HomeAdapter dynamicAdapter;

    String userId;
    BroadcastReceiver broadcastReceiver;
    TrackEvent trackEvent = new TrackEvent();

    public DynamicPage() {
        userId = null;
        setAutoRegisterEventBus(true);
    }

    public static DynamicPage newInstance(String userId) {
        DynamicPage fragment = new DynamicPage();
        fragment.setUserId(userId);
        return fragment;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }


    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_dynamic, container, false);
        unbinder = ButterKnife.bind(this, view);
        dynamicAdapter = new HomeAdapter();
        cdv.config(dynamicAdapter, this);
        cdv.getRecyclerView().setItemAnimator(null);
        dynamicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Moment records = dynamicAdapter.getItem(position);
                switch (records.getSubjectIndex()) {
                    case Moment.SUBJECT_PHOTO_INDEX: {
                        Router.start(records.getRouter());
                        break;
                    }
                    case Moment.SUBJECT_VIDEO_INDEX: {
                        switch (records.getStatus()) {
                            case Moment.STATUS_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(records.getRouter());
                                break;
                        }
                        break;
                    }
                    case Moment.SUBJECT_SPECIAL_TOPIC_INDEX: {
                        switch (records.getStatus()) {
                            case Moment.STATUS_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(records.getRouter());
                                break;
                        }
                        break;
                    }
                    case Moment.SUBJECT_ARTICLE_INDEX: {
                        switch (records.getStatus()) {
                            case Moment.STATUS_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(records.getRouter());
                                break;
                        }
                        break;
                    }
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PublishUtil.ACTION_PUBLISH_PROGRESS_STATUS_UPDATE);
        intentFilter.addAction(PublishUtil.ACTION_UPLOAD_UPDATE);
        getContext().registerReceiver(broadcastReceiver, intentFilter);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        cdv.refresh();
    }

    @Override
    public void onDestroyView() {
        cdv.getRecyclerView().setAdapter(null);
        try {
            getContext().unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().dynamicShow(userId, 20, (int) currentPage);
    }


    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> dynamicMomentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                dynamicMomentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }

            for (Moment item : dynamicMomentList) {
                Moment dynamicMoment = new Moment(item);
                resultList.add(dynamicMoment);
            }

            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    private boolean checkSelf() {
        if (TextUtils.isEmpty(userId)) {
            return false;
        } else {
            return userId.equals(AccountUtil.getCurrentUser().getId());
        }
    }
}
